﻿namespace VectorPicsEditor
{
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using VectorPicsEditor.Properties;
    using System.Linq;

    public partial class Form1 : Form
    {
        private int tabCount;

        public Form1()
        {
            this.InitializeComponent();
            toolStrip1.DataBindings.Add("BackColor", Settings.Default, "WrapperColor", false, DataSourceUpdateMode.OnPropertyChanged);
            tabCount = 0;
        }

        private int NumberOfNonCanvasTabs()
        {
            int result = 0;
            if (this.tabControl.TabPages.ContainsKey("Settings   "))
            {
                ++result;
            }
            return result;
        }

        private void PencilButtonClick(object sender, EventArgs e)
        {
            //don`t draw when haven`t canvas
            if (this.tabControl.TabCount - this.NumberOfNonCanvasTabs() == 0)
                return;
            this.ToolBarButtonClicked(sender as ToolBarButton);
            this.pencilButton.Checked = true;
            (this.tabControl.SelectedTab.Controls[0] as Page).StartDrawing(ShapeType.Pencil);
        }

        private void LineButtonClick(object sender, EventArgs e)
        {
            //don`t draw when haven`t canvas
            if (this.tabControl.TabCount - this.NumberOfNonCanvasTabs() == 0)
                return;
            this.ToolBarButtonClicked(sender as ToolBarButton);
            this.lineButton.Checked = true;
            (this.tabControl.SelectedTab.Controls[0] as Page).StartDrawing(ShapeType.Line);
        }

        private void RectangleButtonClick(object sender, EventArgs e)
        {
            //don`t draw when haven`t canvas
            if (this.tabControl.TabCount - this.NumberOfNonCanvasTabs() == 0)
                return;
            this.ToolBarButtonClicked(sender as ToolBarButton);
            this.rectangleButton.Checked = true;
            (this.tabControl.SelectedTab.Controls[0] as Page).StartDrawing(ShapeType.Rectangle);
        }

        private void EllipseButtonClick(object sender, EventArgs e)
        {
            //don`t draw when haven`t canvas
            if (this.tabControl.TabCount - this.NumberOfNonCanvasTabs() == 0)
                return;
            this.ToolBarButtonClicked(sender as ToolBarButton);
            this.ellipseButton.Checked = true;
            (this.tabControl.SelectedTab.Controls[0] as Page).StartDrawing(ShapeType.Ellipse);
        }
        
        private void ToolBarButtonClicked(ToolBarButton button)
        {
            foreach (var item in this.toolStrip1.Items)
            {
                try
                {
                    (item as ToolStripButton).Checked = false;
                }
                catch (NullReferenceException)
                {
                }
            }
        }

        private void CreateNewButtonClick(object sender, EventArgs e)
        {
            ResizeWindow wnd = new ResizeWindow(553, 465);
            wnd.RatioChecker = false;
            if (DialogResult.Cancel == wnd.ShowDialog(this))
                return;
            this.ToolBarButtonClicked(sender as ToolBarButton);
            this.tabControl.AddTab("Unsaved Image " + ++tabCount);
            Page page = new Page();
            page.SetCanvasSize(wnd.GetWidth(), wnd.GetHeight());
            page.Dock = DockStyle.Fill;
            page.ForgetCanvasChanges();
            this.tabControl.TabPages[this.tabControl.TabPages.Count-1].Controls.Add(page);
            this.tabControl.SelectedIndex = this.tabControl.TabPages.Count - 1;
        }

        private void resizeButton_Click(object sender, EventArgs e)
        {
            if (this.tabControl.SelectedIndex - this.NumberOfNonCanvasTabs() == -1)
                return;
            System.Windows.Size size;
            size = (this.tabControl.SelectedTab.Controls[0] as Page).GetCanvasSize();
            ResizeWindow wnd = new ResizeWindow((int)size.Width, (int)size.Height);
            wnd.RatioChecker = true;
            if (DialogResult.Cancel == wnd.ShowDialog(this))
                return;
            (this.tabControl.SelectedTab.Controls[0] as Page).SetCanvasSize(wnd.GetWidth(), wnd.GetHeight());
        }

        private void saveAsButton_Click(object sender, EventArgs e)
        {
            if (this.tabControl.SelectedIndex - this.NumberOfNonCanvasTabs() == -1)
                return;
            try
            {
                string filename = (this.tabControl.SelectedTab.Controls[0] as Page).SaveAs();
                if (filename != "#")
                {
                    int count = filename.Split('\\').Length;
                    filename = filename.Split('\\')[count - 1];
                    this.tabControl.SelectedTab.Text = filename + "   ";
                }
            }
            catch (System.IO.IOException)
            {
                MessageBox.Show(this, "File in wich you trying to save image now used by program as background.\nPlease try another file.", "File is busy", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            if (this.tabControl.SelectedIndex - this.NumberOfNonCanvasTabs() == -1)
                return;
            try
            {
                string filename = (this.tabControl.SelectedTab.Controls[0] as Page).Save();
                if (filename != "#")
                {
                    int count = filename.Split('\\').Length;
                    filename = filename.Split('\\')[count - 1];
                    this.tabControl.SelectedTab.Text = filename + "   ";
                }
            }
            catch (System.IO.IOException)
            {
                MessageBox.Show(this, "File in wich you trying to save image now used by program as background.\nPlease try another file.", "File is busy", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void openFileButton_Click(object sender, EventArgs e)
        {
            this.tabControl.AddTab("Unsaved Image " + ++tabCount);
            Page page = new Page();
            page.SetCanvasSize(1, 1);
            page.Dock = DockStyle.Fill;
            this.tabControl.TabPages[this.tabControl.TabPages.Count - 1].Controls.Add(page);
            this.tabControl.SelectedIndex = this.tabControl.TabPages.Count - 1;

            string filename = (this.tabControl.SelectedTab.Controls[0] as Page).Open();
            if (filename != "#")
            {
                int count = filename.Split('\\').Length;
                filename = filename.Split('\\')[count - 1];
                this.tabControl.SelectedTab.Text = filename + "   ";
            }
            else // == #
            {
                this.tabControl.TabPages.RemoveAt(this.tabControl.TabPages.Count - 1);
            }
        }

        private void tabControl_ControlRemoved(object sender, ControlEventArgs e)
        {
            TabPage tbp = (sender as TabControl).SelectedTab;
            foreach (Control ctrl in tbp.Controls)
            {
                if (ctrl is Page)
                {
                    (ctrl as Page).Remove();
                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            foreach (TabPage tbp in tabControl.TabPages)
            {
                foreach (Control ctrl in tbp.Controls)
                {
                    if (ctrl is Page)
                    {
                        (ctrl as Page).Remove();
                    }
                }
            }
        }

        private void selectButton_Click(object sender, EventArgs e)
        {
            //don`t draw when haven`t canvas
            if (this.tabControl.TabCount - this.NumberOfNonCanvasTabs() == 0)
                return;
            this.ToolBarButtonClicked(sender as ToolBarButton);
            this.selectButton.Checked = true;
            (this.tabControl.SelectedTab.Controls[0] as Page).StartDrawing(ShapeType.Selector);
        }

        private void zoomButton_Click(object sender, EventArgs e)
        {
            if (this.tabControl.TabCount - this.NumberOfNonCanvasTabs() == 0)
                return;
            Page pg = (this.tabControl.SelectedTab.Controls[0] as Page);
            ZoomWindow wnd = new ZoomWindow(ref pg);
            wnd.ShowDialog();
        }

        private void importButton_Click(object sender, EventArgs e)
        {
            //don`t draw when haven`t canvas
            if (this.tabControl.TabCount - this.NumberOfNonCanvasTabs() == 0)
                return;
            ContextMenuStrip clipboard = new System.Windows.Forms.ContextMenuStrip();
            clipboard.AutoSize = true;
            clipboard.Items.Add("From image");
            clipboard.Items.Add("From clipboard");
            clipboard.ItemClicked += clipboard_Click;

            double x = toolStrip1.PointToClient(MousePosition).X;
            x = ((int)(x / 40)) * 40.0;
            clipboard.Show(toolStrip1, new Point((int)x, clipboardStripButton.Height));
        }

        private void clipboard_Click(object sender, ToolStripItemClickedEventArgs e)
        {
            string str = e.ClickedItem.Text;
            (sender as ContextMenuStrip).Dispose();
            if (str == "From image")
                (this.tabControl.SelectedTab.Controls[0] as Page).ImportImage();
            else
                (this.tabControl.SelectedTab.Controls[0] as Page).LoadFromClipboard();
        }

        private void textButton_Click(object sender, EventArgs e)
        {
            //don`t draw when haven`t canvas
            if (this.tabControl.TabCount - this.NumberOfNonCanvasTabs() == 0)
                return;
            this.ToolBarButtonClicked(sender as ToolBarButton);
            this.textButton.Checked = true;
            (this.tabControl.SelectedTab.Controls[0] as Page).StartDrawing(ShapeType.TextBlock);
        }

        private void backgroundButton_Click(object sender, EventArgs e)
        {
            //don`t draw when haven`t canvas
            if (this.tabControl.TabCount - this.NumberOfNonCanvasTabs() == 0)
                return;
            (this.tabControl.SelectedTab.Controls[0] as Page).ChangeBackGround();
        }

        private void clipboardStripButton_Click(object sender, EventArgs e)
        {
            //don`t draw when haven`t canvas
            if (this.tabControl.TabCount - this.NumberOfNonCanvasTabs() == 0)
                return;
            (this.tabControl.SelectedTab.Controls[0] as Page).CopyToClipboard();
        }

        public static void DeleteDirectory(string target_dir)
        {
            string[] files = System.IO.Directory.GetFiles(target_dir);
            string[] dirs = System.IO.Directory.GetDirectories(target_dir);

            foreach (string file in files)
            {
                System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
                System.IO.File.Delete(file);
            }

            foreach (string dir in dirs)
            {
                DeleteDirectory(dir);
            }

            System.IO.Directory.Delete(target_dir, false);
        }

        private void ReloadIcons()
        {
            int type = Settings.Default.IconsType == "Clasic" ? 1 : 2;
            createNewButton.Image = type==1?(Image)Resources.createNew_1:(Image)Resources.createNew_2;
            openFileButton.Image = type == 1 ? (Image)Resources.openFile_1 : (Image)Resources.openFile_2;
            saveButton.Image = type == 1 ? (Image)Resources.save_1 : (Image)Resources.save_2;
            saveAsButton.Image = type == 1 ? (Image)Resources.saveAs_1 : (Image)Resources.saveAs_2;
            resizeButton.Image = type == 1 ? (Image)Resources.resize_1 : (Image)Resources.resize_2;
            zoomButton.Image = type == 1 ? (Image)Resources.zoom_1 : (Image)Resources.zoom_2;
            selectButton.Image = type == 1 ? (Image)Resources.select_1 : (Image)Resources.select_2;
            importButton.Image = type == 1 ? (Image)Resources.import_1 : (Image)Resources.import_2;
            pencilButton.Image = type == 1 ? (Image)Resources.pencil_1 : (Image)Resources.pencil_2;
            lineButton.Image = type == 1 ? (Image)Resources.line_1 : (Image)Resources.line_2;
            rectangleButton.Image = type == 1 ? (Image)Resources.rectangle_1 : (Image)Resources.rectangle_2;
            ellipseButton.Image = type == 1 ? (Image)Resources.ellipse_1 : (Image)Resources.ellipse_2;
            textButton.Image = type == 1 ? (Image)Resources.text_1 : (Image)Resources.text_2;
            backgroundButton.Image = type == 1 ? (Image)Resources.background_1 : (Image)Resources.background_2;
            clipboardStripButton.Image = type == 1 ? (Image)Resources.clipboard_1 : (Image)Resources.clipboard_2;
            settingsStripButton.Image = type == 1 ? (Image)Resources.settings_1 : (Image)Resources.settings_2;
            helpStripButton.Image = type == 1 ? (Image)Resources.help_1 : (Image)Resources.help_2;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.ReloadIcons();
            //Delete old buffer elements
            string curPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Buffer");
            if (System.IO.Directory.Exists(curPath))
                DeleteDirectory(curPath);
        }

        private void settingsStripButton_Click(object sender, EventArgs e)
        {
            if (this.tabControl.TabPages.ContainsKey("Settings   "))
            {
                this.tabControl.SelectedIndex = this.tabControl.TabPages.IndexOfKey("Settings   ");
            }
            else
            {
                this.tabControl.AddTab("Settings");
                SettingPage page = new SettingPage();
                page.StyleChanged += ReloadStyle;
                page.Dock = DockStyle.Fill;
                this.tabControl.TabPages[this.tabControl.TabPages.Count - 1].Controls.Add(page);
                this.tabControl.SelectedIndex = this.tabControl.TabPages.Count - 1;
            }
        }

        private void ReloadStyle(object sender, PropertyValueChangedEventArgs e)
        {
            this.ReloadIcons();
        }

        private void helpStripButton_Click(object sender, EventArgs e)
        {
            //Help
        }

    }
}